package net.hzlj.platform.enterprise.helper;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.google.gson.Gson;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.beans.ui.LocationBean;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.socket.SocketManager;
import net.hzlj.platform.enterprise.utils.AppPreferencesUtils;
import net.hzlj.platform.enterprise.utils.PreferencesUtils;
import net.hzlj.platform.enterprise.utils.StringUtils;
import net.hzlj.rl.zhangjiajie.R;
import net.hzlj.platform.enterprise.provider.AccountProvider;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * @Description: 实时定位管理
 * @Author: Jason Zhang
 * @Date: 2017/2/17 0017
 */

public class RealTimeLocationManager {

    private static final String TAG = RealTimeLocationManager.class.getSimpleName();

    private LocationBean mLocationBean = new LocationBean();

    //位置上传
    private Subscription mUploadLocationSubscription;

    private static RealTimeLocationManager instance = new RealTimeLocationManager();

    private static Context mContext = BootApp.getAppContext();

    private boolean isRunning = false;

    private boolean isFirstUploadLocation = false;

    private boolean isReportOnce = false;//上报一次开关

    public static RealTimeLocationManager getInstance() {
        return instance;
    }

    private RealTimeLocationManager() {

    }

    public void startLocation() {
        Log.i(TAG,"startLocation......");
        updateLocationTime();
        isRunning = true;
        addAccount();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);//电池变化
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//电池变化
        mContext.registerReceiver(mInitBroadcastReceiver, filter);
    }

    //新增賬戶模块
    private void addAccount() {
        AccountManager accountManager = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);
        Account account = null;
        Account[] accounts = accountManager.getAccountsByType("net.hzlj.rl.zhangjiajie.authaccount");
        if (accounts != null && accounts.length > 0) {
            account = accounts[0];
        } else {
            account = new Account(mContext.getString(R.string.app_title), "net.hzlj.rl.zhangjiajie.authaccount");
        }
        if (accountManager.addAccountExplicitly(account, null, null)) {
            //开启同步，并设置同步周期
            ContentResolver.setIsSyncable(account, AccountProvider.AUTHORITY, 1);
            ContentResolver.setSyncAutomatically(account, AccountProvider.AUTHORITY, true);
            ContentResolver.addPeriodicSync(account, AccountProvider.AUTHORITY, new Bundle(), 10);
        }
    }

    public void updateLocationTime() {
        Log.i(TAG,"updateLocationTime......");
        isFirstUploadLocation = false;
        int locationInterval = AppPreferencesUtils.getInt(BootApp.getAppContext(), PreferencesUtils.KEY_LOCATION_INTERVAL, Constant.Socket.DEFAULT_LOCATION_TIME);
        Log.i(TAG,"locationInterval:" + locationInterval);
        BaiduLBSManager.getInstance().refreshLocationTime(mBDLocationListener);
        if (!BaiduLBSManager.getInstance().getLocationClient().isStarted()) {
            BaiduLBSManager.getInstance().getLocationClient().start();
        }
        if (mUploadLocationSubscription != null){
            mUploadLocationSubscription.unsubscribe();
            mUploadLocationSubscription = null;
        }
        mUploadLocationSubscription = Observable.interval(0, locationInterval * 1000, TimeUnit.MILLISECONDS).filter(new Func1<Long, Boolean>() {
            @Override
            public Boolean call(Long aLong) {
                isRunning = true;
                return BootApp.isConnect() && BootApp.getInstance().isLogin() && SocketManager.getInstance().isConnection();
            }
        }).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                String message = getLocationMessage();
                Log.i(TAG,"Long:" + aLong + ",message:" + message);
                if (StringUtils.isNotEmpty(message)){
                    BootApp.getInstance().sendBroadcast(Constant.Intent.ACTION_SOCKET_MESSAGE_SEND,message);
                    isFirstUploadLocation = true;
                    if (isReportOnce){
                        mLocationBean.setCommandId(null);
                        mLocationBean.setMessage(null);
                        mLocationBean.setType(0);
                        isReportOnce = false;
                    }
                }
            }
        });

    }

    private BroadcastReceiver mInitBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String action = intent.getAction();
            Log.i(TAG, "mLocateBroadcastReceiver action:" + action);
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                //获取当前电量
                int level = intent.getIntExtra("level", 0);
                //电量的总刻度
                int scale = intent.getIntExtra("scale", 100);
                mLocationBean.setElectric(String.valueOf((level * 100) / scale));
            }
        }
    };

    private BDLocationListener mBDLocationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            mLocationBean.setLongitude(String.valueOf(location.getLongitude()));
            mLocationBean.setLatitude(String.valueOf(location.getLatitude()));
            mLocationBean.setPosition(location.getAddrStr());
            if (!isFirstUploadLocation){
                BootApp.getInstance().sendBroadcast(Constant.Intent.ACTION_SOCKET_MESSAGE_SEND,getLocationMessage());
                if (isReportOnce){
                    mLocationBean.setCommandId(null);
                    mLocationBean.setMessage(null);
                    mLocationBean.setType(0);
                    isReportOnce = false;
                }
                isFirstUploadLocation = true;
            }
        }
    };

    public void reportOnceLocation(LocationBean bean){
        isReportOnce = true;
        mLocationBean.setMessage(bean.getMessage());
        mLocationBean.setType(bean.getType());
        mLocationBean.setCommandId(bean.getCommandId());
        updateLocationTime();
        //BootApp.getInstance().sendBroadcast(Constant.Intent.ACTION_SOCKET_MESSAGE_SEND,getLocationMessage());
    }

    public String getLocationMessage() {
        if (StringUtils.isNotEmpty(mLocationBean.getPosition()) && BootApp.getInstance().isLogin()) {
            mLocationBean.setId(BootApp.getInstance().getUserTelephone());
            mLocationBean.setTime(System.currentTimeMillis() + "");
            return new Gson().toJson(mLocationBean);
        }
        return "";
    }

    public boolean isRunning(){
        return this.isRunning;
    }

    public void destroy() {
        isRunning = false;
        if (BaiduLBSManager.getInstance().getLocationClient() != null) {
            BaiduLBSManager.getInstance().getLocationClient().stop();
        }
        if (mContext != null && mInitBroadcastReceiver != null){
            try {
                mContext.unregisterReceiver(mInitBroadcastReceiver);
                mInitBroadcastReceiver = null;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (mUploadLocationSubscription != null){
            mUploadLocationSubscription.unsubscribe();
        }
        mUploadLocationSubscription = null;
        isFirstUploadLocation = false;
    }
}
